package com.itheima.reggie.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.util.ListUtils;
import com.itheima.reggie.entity.Employee;
import com.itheima.reggie.service.EmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.DigestUtils;

import java.util.List;

@Slf4j
public class UploadListener extends AnalysisEventListener<Employee> {

    /**
     * 注意: 由于当前UploadDataListener是我们new出来的, 类的对象不在Spring容器中, 因此不能使用 @Autowired注入 ExcelService
     */
    private  EmployeeService employeeService;
    /**
     * 每隔5条存储数据库，实际使用中可以100条，然后清理list ，方便内存回收
     */
    private static final int BATCH_COUNT = 5;
    //创建一个初始化容量大小的list集合，都是为了节约内存空间
    private List<Employee> employeesList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);

    public UploadListener(EmployeeService employeeService) {
        this.employeeService = employeeService;
    }
    @Override
    public void invoke(Employee employee, AnalysisContext analysisContext) {
        log.info(":解析到一条数据{}", employee);
        employee.setPassword(DigestUtils.md5DigestAsHex("123456".getBytes()));
        employeesList.add(employee);
        if (employeesList.size()>=BATCH_COUNT){
            saveData();
            employeesList=ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {

        if (employeesList.size()>=1){
            saveData();
        }
        log.info("所有数据解析完成");
    }

    private void saveData(){
        employeeService.saveBatch(employeesList);
        log.info("存储数据库成功");
    }
}
